package handler

import (
	"course/api/request"
	"course/consts"
	"course/interal/dao"
	"course/interal/model"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{}, &user)
	if user.Mobile == req.Mobile {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "此用户已存在",
			"data": nil,
		})
		return
	}
	if len(req.Password) != 8 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "密码长度必须为8位",
			"data": nil,
		})
		return
	}
	//str := "^[0-9][A-Za-z]$"
	//if req.Password != str {
	//	c.JSON(http.StatusOK, gin.H{
	//		"code": 10000,
	//		"msg":  "密码格式必须是字母加数字",
	//		"data": nil,
	//	})
	//	return
	//}
	user = model.Users{
		Mobile:   req.Mobile,
		PassWord: req.Password,
	}
	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": user,
	})
}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{Mobile: req.Mobile}, &user)
	if user.Mobile != req.Mobile {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "没有次用户",
			"data": nil,
		})
		return
	}
	if len(req.Password) != 8 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "密码长度必须为8位",
			"data": nil,
		})
		return
	}
	//str := `^[0-9][A-Za-z]$`
	//if req.Password != str {
	//	c.JSON(http.StatusOK, gin.H{
	//		"code": 10000,
	//		"msg":  "密码格式必须是字母加数字",
	//		"data": nil,
	//	})
	//	return
	//}
	token, err := jwt2.NewJWT(consts.JWT_KEY).CreateToken(jwt2.CustomClaims{
		ID: uint(user.Id),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().UnixMilli() + 86400*7,
		},
	})
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": token,
	})
}

func FindUser(c *gin.Context) {

	var user []model.Users
	var users []*model.Users
	dao.GetListByFields(&model.Users{}, &user)
	for _, v := range user {
		users = append(users, &v)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": users,
	})

}
